<?php
namespace App\Services;

use App\MenuPermission;
use App\BaseDictionary;
use App\Lib\Util\QueryPager;

class PermissionService
{
    public function createMenuPermission($menuPermission)
    {
        return MenuPermission::create($menuPermission);
    }

    public function getPermissions(Array $input){

        $menu_name = $input['menu_name'];

        if(empty($menu_name)){
            $query = \App\MenuPermission::select('*');
        }else{
            $query = \App\MenuPermission::where('name','like',"%".$menu_name."%");
        }

        $pager = new QueryPager($query);

        $pager->mapField('permission_type', MenuPermission::$PERMISSION_TYPE_MAP);
        $pager->mapField('is_default', MenuPermission::$IS_DEFAULT_MAP);

        return $pager->doPaginate($input,'sort_order');
    }

    public function getRows(Array $input){

        $id = $input['id'];

        $query = \App\MenuPermission::where('id',$id)->get();

        return $query;
    }

    public function getParent(Array $input){

        $permission_type = ($input['pid'] - 1)>0?($input['pid'] - 1):0;

        $query = \App\MenuPermission::where('permission_type',$permission_type)->get();

        return $query;
    }

    public function getSibling(Array $input){

        $permission_type = ($input['permission_type'])>0?($input['permission_type']):0;

        $query = \App\MenuPermission::where('permission_type',$permission_type)->get();

        return $query;
    }

    public function savePermission(Array $input){

        $permission = new \App\MenuPermission();
        $permission->fill($input);
        $insert = $permission->save();

        if(empty($insert)){
            $success = false;
        }else{
            $success = true;
        }

        return response()->json([
            "Success"=>$success,
        ]);
    }

    public function updatesavePermissions(Array $input){

        $id = $input['id'];

        unset($input[array_search("id",$input)]);

        $update = \App\MenuPermission::where("id",$id)->update($input);

        if(empty($update)){
            $success = false;
        }else{
            $success = true;
        }

        return response()->json([
            "Success"=>$success,
        ]);
    }

    public function delPermissions(Array $input){

        $id = $input['id'];
        $permission = new \App\MenuPermission();
        $permission->fill($input);
        $insert = $permission->save();

        $delstate = \App\MenuPermission::destroy($id);

        if(empty($delstate)){
            $success = false;
        }else{
            $success = true;
        }

        return response()->json([
            "Success"=>$success,
        ]);
    }
}
